using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Awaken.Framework
{
    /// <summary>
    /// Represents the entry point into the Awaken peristence framework.
    /// </summary>
    /// <remarks>
    /// Follows the Gateway Pattern described by Martin Fowler here:
    /// http://www.martinfowler.com/eaaCatalog/gateway.html
    /// From the article: "Wrap all the special API code into a class whose interface 
    /// looks like a regular object. Other objects access the resource through this 
    /// Gateway, which translates the simple method calls into the appropriate 
    /// specialized API."
    /// </remarks>
    public class Gateway
    {
        private Hashtable mTypeToDatabaseTable = new Hashtable();

        /// <summary>
        /// Mapping of databases to the types that they contain.
        /// </summary>
        public Hashtable TypeToDatabaseTable
        {
            get { return mTypeToDatabaseTable; }
        }
        
        private Collection<Database> mDatabases = new Collection<Database>();
        
        /// <summary>
        /// Gets or sets the list of databases controlled by this gateway.
        /// </summary>
        public Collection<Database> Databases
        {
            get { return mDatabases; }
        }

        private static Gateway mInstance;
        
        /// <summary>
        /// Gets the global gateway. Follows the Singleton design pattern.
        /// </summary>
        public static Gateway Instance
        {
            get
            {
                if ( mInstance == null)
                {
                     mInstance = GatewayFactory.CreateGateway();
                }
                return mInstance;
            }
        }
        
        /// <summary>
        /// Gets the connection string used for accessing the given
        /// database.  If no connection string is found an empty value
        /// is returned.
        /// </summary>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public static string GetConnectionString(string databaseName)
        {
            string conn = null;

            foreach (Database db in Instance.Databases)
            {
                if (db.Name == databaseName)
                {
                    conn = db.ConnectionString;
                    break;
                }
            }
            return conn;
        }

        /// <summary>
        /// Returns all of the mapped types.
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// NHibernate loads all mapped types for ALL databases
        /// into each databases configuration.  So you only need to
        /// pull the mapped types for the first database, in order to
        /// see the types for ALL databases.
        /// </remarks>
        public static Collection<Type> MappedTypes
        {
            get
            {
                //TODO: Clarify this, perhaps filter types so they are db specific
                //      then combine the list here for the sake of clarity.
                return Instance.Databases[0].MappedTypes;
            }
        }

        /// <summary>
        /// Saves the given entity.
        /// </summary>
        /// <param name="obj"></param>
        public static void Save(object entity)
        {
            if (entity == null)
            {
                throw new AwakenException(Messages.NullEntity);
            }

            GetDatabaseFor(entity.GetType()).Save(entity);
        }

        /// <summary>
        /// Deletes the given entity.
        /// </summary>
        /// <param name="obj"></param>
        public static void Delete(object entity)
        {
            if (entity == null)
            {
                throw new AwakenException(Messages.NullEntity);
            }
            GetDatabaseFor(entity.GetType()).Delete(entity);
        }

        /// <summary>
        /// Returns the Database object responsible for managing the
        /// given type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Database GetDatabaseFor(System.Type type)
        {
            Database result = null;

            if (type == null)
            {
                throw new AwakenException(Messages.NullType);
            }

            if (!Instance.TypeToDatabaseTable.ContainsKey(type.ToString()))
            {
                throw new AwakenException(Messages.NoDatabaseForType);
            }

            result = (Database)Instance.TypeToDatabaseTable[type.ToString()];

            if (result == null)
            {
                throw new AwakenException(Messages.NoDatabaseForType);
            }
            return result;
        }

        /// <summary>
        /// Returns the instance of the given type with the given ID.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static object GetByID(System.Type type, object id)
        {
            return GetDatabaseFor(type).GetByID(type, id);
        }

        /// <summary>
        /// Returns all instances of the given type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IList GetAll(System.Type type)
        {
            return GetDatabaseFor(type).GetAll(type);
        }

        /// <summary>
        /// Returns a list of objects of the given type
        /// based on the given query.  The query should be written
        /// in NHibernate query language.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static IList GetByQuery(System.Type type,string query)
        {
            if (String.IsNullOrEmpty(query))
                return null;

            return GetDatabaseFor(type).CurrentSession.Find(query);
        }

        /// <summary>
        /// Begins a transaction.
        /// </summary>
        /// <param name="type"></param>
        public static void BeginTransaction(System.Type type)
        {
            // TODO: It is not intuitive to start a transaction for 
            //       a type.
            GetDatabaseFor(type).BeginTransaction();
        }

        /// <summary>
        /// Commits a transaction.
        /// </summary>
        /// <param name="type"></param>
        public static void CommitTransaction(System.Type type)
        {
            GetDatabaseFor(type).CommitTransaction();
        }

        /// <summary>
        /// Aborts a transaction.
        /// </summary>
        /// <param name="type"></param>
        public static void RollbackTransaction(System.Type type)
        {
            GetDatabaseFor(type).RollbackTransaction();
        }

        /// <summary>
        /// Closes all sessions in all databases.
        /// </summary>
        public static void CloseSessions()
        {
            foreach (Database database in Instance.Databases)
            {
                database.CloseSession();
            }
        }
    }
}